from flask import request
from flask_classy import FlaskView, route

from auth.services.auth import AuthService
from auth.services.session import SessionService
from ..schema.error import LOCAL_AUTH_NOT_EXIST
from ..schema.param import register_local_param
from ..schema.resp import login_name_is_exist, token_schema, OrderSchema, query_schema, order_list
from ..services.member import MemberService


class MembersView(FlaskView):
    @route('/register', methods=['POST'])
    def register_local(self):
        params, errors = register_local_param.load(request.get_json())
        login_name = params.pop('login_name')
        password = params.pop('password')
        member_info = params.pop('member_info')
        channel = params.pop('channel', None)
        member_id = create_member_id(channel)

        local_auth = AuthService.fetch_local_auth_by_login_name(login_name)
        if local_auth:
            return login_name_is_exist.jsonify()

        screen_name = params.pop('screen_name', None)
        # TODO 默认用户名需要可配置
        screen_name = 'vosuser'

        # TODO 默认头像需要可配置
        head_image_id = params.pop('head_image_id', None)
        if not head_image_id:
            from ..services.resource import ResourceService
            head_image_id = ResourceService.random().id
        member = MemberService.create_member(id=member_id, screen_name=screen_name, head_image_id=head_image_id,
                                             **member_info)
        local_auth = AuthService.create_local_auth(
            login_name=login_name,
            password=password,
            type='member',
            profile_id=member_id
        )
        return token_schema.jsonify(SessionService.create_local_token(local_auth))

    @route('/<member_id>/orders', methods=['GET'])
    def get_member_order(self, member_id):
        member = MemberService.get_member_by_id(member_id)
        if member:
            member_orders, pagination = MemberService.get_orders_by_member(member_id)
        else:
            return LOCAL_AUTH_NOT_EXIST.jsonify()
        return query_schema.jsonify_with(items=order_list.dump(member_orders).data,
                                       pagination=pagination
                                       )

def create_member_id(channel):
    channel_code = '09'
    if channel == 'web':
        channel_code = '10'
    import time
    import random
    now = time.localtime(time.time())
    year = now.tm_year - 1970
    day = now.tm_yday

    random_id = random.randint(1, 9999999)
    if random_id < 1000:
        random_id = str(random_id).zfill(4)
    return '{channel}{year}{day}{random}'.format(
        channel=channel_code,
        year=year,
        day=day,
        random=random_id
    )
